<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键词" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="一级类目" prop="firstLevelColumn">
        <!-- <el-input v-model="queryParams.firstLevelColumn" placeholder="请输入一级类目" clearable
          @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.firstLevelColumn" placeholder="请选择一级类目" clearable>
          <el-option v-for="dict in dict.type.sys_product_pl" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="尺码表图片" prop="sizeUrl">
        <el-input v-model="queryParams.sizeUrl" placeholder="请输入尺码表图片" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:size:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['product:size:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['product:size:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['product:size:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sizeList" @selection-change="handleSelectionChange"
      :row-style="{ height: '100px' }">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="关键词" align="center" prop="keyword" />
      <el-table-column label="一级类目" align="center" prop="firstLevelColumn" />
      <!-- <el-table-column label="尺码表图片" align="center" prop="sizeUrl" /> -->
      <el-table-column label="尺码表图片" align="center" prop="sizeUrl">
        <template #default="scope">
          <el-popover effect="light" trigger="click" placement="left" width="auto" v-show="scope.row.sizeUrl">
            <template #default>
              <img :src='pjtUrl + scope.row.sizeUrl' style="width: 800px;height: 600px;object-fit: contain;">
            </template>
            <template #reference>
              <img :src='pjtUrl + scope.row.sizeUrl' style="width: 100px; height: 100px;object-fit: contain;" />
            </template>
          </el-popover>
        </template>
        <!-- <template slot-scope="scope">
                                                                  <el-image style="width: 100px; height: 100px" :src="scope.row.logoFullUrl"></el-image></template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['product:size:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['product:size:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改客服尺码数据字典对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="form.keyword" placeholder="请输入关键词" />
        </el-form-item>
        <el-form-item label="一级类目" prop="firstLevelColumn">
          <!-- <el-input v-model="form.firstLevelColumn" placeholder="请输入一级品类" /> -->
          <el-select v-model="form.firstLevelColumn" placeholder="请选择一级类目" clearable>
            <el-option v-for="dict in dict.type.sys_product_pl" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="尺码表图片" prop="sizeUrl">
          <el-input v-model="form.sizeUrl" placeholder="请输入尺码表图片" />
        </el-form-item> -->
        <el-form-item label="尺码表图片" prop="purchasingAfterPicurl" label-width="40">
          <el-upload :action="imgUpload.url" :headers="imgUpload.headers" list-type="picture-card" :limit="limit"
            :on-exceed="handleExceed" :on-success="handlePictureSuccessPic" :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview" :file-list="fileList" :on-change="changeFile2">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" v-if="purchasingAfterPicurl" :src="pjtUrl + purchasingAfterPicurl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { listCustomsize, getCustomsize, delCustomsize, addCustomsize, updateCustomsize } from "@/api/product/customsize";
import { listSize, getSize, delSize, addSize, updateSize } from "@/api/data/size";
//--------导入token
import { getToken } from "@/utils/auth";
// import { json } from "node:stream/consumers";
export default {
  name: "Size",
  dicts: ['sys_product_qudao', 'sys_product_size', 'sys_product_design', 'sys_product_scene', 'sys_product_coder', 'sys_product_yf', 'sys_product_cycle', 'sys_product_pl'],
  data() {
    return {
      purchasingAfterPicurl: '',

      pjtUrl: process.env.VUE_APP_BASE_API,
      // 图片数量限制
      limit: 2,
      //页面上存的暂时图片地址List
      // files: [{ url: "" }],
      files: [],
      fileList: [],
      dialogVisible: false,
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客服尺码数据字典表格数据
      sizeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        firstLevelColumn: null,
        sizeUrl: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        keyword: [
          { required: true, message: "关键词不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客服尺码数据字典列表 */
    getList() {
      this.loading = true;
      listSize(this.queryParams).then(response => {
        this.sizeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        keyword: null,
        firstLevelColumn: null,
        sizeUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客服尺码数据字典";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSize(id).then(response => {
        this.fileList = response.data.sizeUrl ? [
          { url: process.env.VUE_APP_BASE_API + response.data.sizeUrl }] : []//logo图片加的是这一行
        // this.files = response.data.purchasingBeforePicurl ? [
        //             { url: process.env.VUE_APP_BASE_API + response.data.purchasingBeforePicurl }] : []//图片加的是这一行
        this.form = response.data;
        console.log(JSON.stringify(response.data));
        this.open = true;
        this.title = "修改客服尺码数据字典";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.sizeUrl = this.purchasingAfterPicurl
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSize(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSize(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客服尺码数据字典编号为"' + ids + '"的数据项？').then(function () {
        return delSize(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/size/export', {
        ...this.queryParams
      }, `size_${new Date().getTime()}.xlsx`)
    },
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isJPG && isLt2M;
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.purchasingBeforePicurl
        = file.url
      this.purchasingAfterPicurl = file.url
      // this.imageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureSuccessPic(res, file) {
      this.purchasingAfterPicurl = file.response.fileName;
    },
    //图片修改前的回调
    handlePictureSuccess(res, file) {
      //设置图片访问路径 （url 后台传过来的的上传地址）
      // this.imageUrl = file.response.url;
      // const url = file.response.fileName;
      this.purchasingBeforePicurl = file.response.fileName;
      // console.log(JSON.stringify(url));
    },

    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传链接LOGO图片数量不能超过 ${this.limit} 个!`);
    },
    changeFile1(file, fileList) {
      if (fileList.length > 1) {
        this.files = fileList.slice(-1);

        // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }
      // this.fileSpecial = fileList;
    },
    changeFile2(file, fileList) {
      if (fileList.length > 1) {
        this.fileList = fileList.slice(-1);

        // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }
      // this.fileSpecial = fileList;
    },
  }
};
</script>
